package kr.hkit.powerjava.chapter24.work;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;



public class StudentDao implements InterfaceDao<Student> {
	private ArrayList<Student> lists;
	private static final String FILE_NAME = "studentList.data";

	@Override
	public void insertItem(Student Item) {
		if (!lists.contains(Item)){
			lists.add(Item);
		} else {
			System.out.println("중복된 데이터");
		}
	}

	@Override
	public void deleteItem(Student Item) { //idx = 삭제할 학번(stdNum)
		lists.remove(Item);
	}

	@Override
	public void updateItem(Student Item) {
		lists.set(lists.indexOf(Item), Item);
	}

	@Override
	public Student searchItem(Student Item) {
		return lists.get(lists.indexOf(Item));
	}

	@Override
	public void prnItemList(Comparator<Student> comp) {
		if (comp == null){
			Collections.sort(lists);
		} else {
			Collections.sort(lists, comp);
		}
		for (Student std : lists){
			System.out.println(std);
		}
	}

	@Override
	public void loadFile() {
		ObjectInputStream ois = null;
		try {
			ois = new ObjectInputStream(new BufferedInputStream(new FileInputStream(FILE_NAME)));
			lists = (ArrayList<Student>) ois.readObject();
			
		} catch (FileNotFoundException e) {
			try {
				new File(StudentDao.FILE_NAME).createNewFile();
				lists = new ArrayList<>();
			} catch (IOException e1) {}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (ois != null) try { ois.close();	} catch (Exception e) {}
		}

	}

	@Override
	public void saveFile() {
		ObjectOutputStream oos =  null;
		try {
			oos = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(FILE_NAME)));
			oos.writeObject(lists);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (oos != null) try  {oos.close();} catch (Exception e) {}
		}
	}

}
